import { AudioSource, AudioClip } from 'cc';
import { BaseClass } from './BaseClass';
import { AbNames } from '../../../Game/Scripts/Config/ResConfig';
import { ResManager } from './ResManager';
/**
 * @en
 * this is a sington class for audio play, can be easily called from anywhere in you project.
 * @zh
 * 这是一个用于播放音频的单件类，可以很方便地在项目的任何地方调用。
 */ 
export let AudioCfg = {
    sound_effectKey:'sound_effectKey',
    sound_musicKey:'sound_musicKey',
}

export class AudioMgr extends BaseClass{
    public volumeCur: number = 1;

    private static _inst: AudioMgr;
    public static get inst(): AudioMgr {
        if (this._inst == null) {
            this._inst = new AudioMgr();
        }
        return this._inst;
    }

    private _audioSource: AudioSource;
    private _audioEffect: AudioSource;
    constructor() {
        super()    
        //背景音乐
        this._audioSource = this.rootNode.addComponent(AudioSource);
        //音效
        this._audioEffect = this.rootNode.addComponent(AudioSource);
    }

    public get audioSource() {
        return this._audioSource;
    }

    /**
     * @en
     * play short audio, such as strikes,explosions
     * @zh
     * 播放短音频,比如 打击音效，爆炸音效等
     * @param sound clip or url for the audio
     * @param volume 
     */
    playOneShot(abName: string = AbNames.Common, path: string = 'Sounds/click', volume: number = this.volumeCur) {
        if(!this._audioEffect){
            return
        }
        let siOpen = localStorage.getItem(AudioCfg.sound_effectKey);
        if(parseInt(siOpen) == 0){
            return;
        }
        let clip = ResManager.inst.getAsset(abName,path,AudioClip) as AudioClip;
        if(clip){
            this._audioEffect.playOneShot(clip, volume);
        }
    }

    //停止音效
    stopOneShot(isStop: Boolean){
        if(!isStop){
            this._audioEffect.destroy() ;
            this._audioEffect = null;
        }else{
            if(!this._audioEffect ){
                this._audioEffect = this.rootNode.addComponent(AudioSource);
            }
        }
    }

    /**
     * 
     * @param abName ab包名
     * @param path 路径
     * @param volume 声音大小
     * @param isLoop 是否循环
     */
    play(abName: string, path: string, volume: number = 1.0,isLoop: boolean = true) {
        let clip = ResManager.inst.getAsset(abName,path,AudioClip) as AudioClip;
        this._audioSource.stop();
        this._audioSource.clip = clip;
        this._audioSource.play();
        this._audioSource.loop = isLoop;
        this.audioSource.volume = volume;
    }

    /**
     * stop the audio play
     */
    stop() {
        this._audioSource.stop();
    }

    /**
     * pause the audio play
     */
    pause() {
        this._audioSource.pause();
    }

    /**
     * resume the audio play
     */
    resume(){
        this._audioSource.play();
    }

    isPlaying(): Boolean{
        return this._audioSource.playing;
    }
}

